package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class PublishApiImpl implements PublishApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Publish findById(String publishId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(publishId));
        return mongoTemplate.findOne(query,Publish.class);
    }

    @Override
    public PageResult findPublishList(Integer page, Integer pagesize, Long uid) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(uid));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page-1,pagesize));
        List<Publish> publishes = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);
        int pages = (int) Math.ceil(count*1.0/pagesize);
        return new PageResult((int) count,pagesize,pages,page,publishes);
    }

    @Override
    public void update(Publish publish) {
        Query query = new Query().addCriteria(Criteria.where("id").is(publish.getId()));
        Update update = new Update().set("state",publish.getState());
        mongoTemplate.updateFirst(query,update ,Publish.class);
    }

    @Override
    public List<Publish> findPublishByPid(ArrayList<Long> pids) {
        Query query = new Query().addCriteria(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query, Publish.class);

    }
}
